package com.my.study.excel.Import;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.my.study.excel.constant.ExcelConstant;
import com.my.study.exception.BusinessException;

import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

public abstract class BaseExcelImportServiceImpl<T> extends AnalysisEventListener<T> implements ExcelImportService {

    private List<T> importDataList = new CopyOnWriteArrayList<>();

    private static final int MAX_SHEET = ExcelConstant.MAX_SHEET;

    @Override
    public abstract long getSheetImportNum();

    @Override
    public abstract int importTotalSheetNum();

    @Override
    public abstract <T> boolean importData(List<T> data);

    public void invoke(T data, AnalysisContext analysisContext) {
        importDataList.add(data);
        if (importTotalSheetNum() > MAX_SHEET) {
            throw BusinessException.fail("sheet页超出限制!");
        }
        if (importDataList.size() >= getSheetImportNum()) {
            importData(importDataList);
            importDataList.clear();
        }
    }

    public void doAfterAllAnalysed(AnalysisContext var1) {
        importData(importDataList);
        importDataList.clear();
    }
}
